<script setup>
import { useMessage, NButton, NIcon, darkTheme, NModal, NCard, NInput, NInputGroup, NUpload, NPopconfirm, NSpin, NDatePicker } from 'naive-ui'
import PostEditor from '@/components/icons/PostEditor.vue'
import PostDelete from '@/components/icons/PostDelete.vue'
import { defineProps, ref, onBeforeUpdate } from 'vue'
import { useStore } from '@/stores/index'
import axios from 'axios'
import { useRouter } from 'vue-router';

// 定义文章IDProps
const { postData } = defineProps({
  postData: {
    name: 'post-data',
    type: Object,
    required: true
  }
});

const message = useMessage()  // 获取message实例
const router = useRouter()  // 获取路由实例
const backedHost = useStore().$state.backedHost // 后端API前缀
const token = localStorage.getItem('token')  // 用户token

const showDeleteModal = ref(false)  // 是否显示删除文章弹窗
const showEditModal = ref(false)  // 是否显示编辑文章弹窗
const editBtn = ref(false)  // 是否显示编辑提交按钮
const uploadImageObj = ref({})  // 当前文件上传ID对应的后端图片ID


// 删除上传的图片
function deleteImage(fileData) {
  
  editBtn.value = false  // 禁用编辑按钮
  const fetchConfig = {
    method: 'post',
    headers: { Authorization: 'Bearer ' + token },
    url: backedHost + '/image/delete_image?id=' + uploadImageObj.value[fileData.file.id]
  }
  axios(fetchConfig)
    .then((response) => {
      if (response.data.code === 2000) {
        message.success('删除成功！')
      }
      editBtn.value = true  // 启用编辑按钮
    })
    .catch((error) => {
      console.log(error)
      message.error(error.response.data.message)
      editBtn.value = true  // 启用编辑按钮
    })  
}

// 当前编辑文章信息
const updatePost = ref({
  id: postData.id,  // 文章ID
  title: postData.title,  // 文章标题
  content: postData.content,  // 文章内容
  image_ids: postData.image_ids,  // 文章图片ID列表（逗号分割的）
  create_timestamp: postData.create_timestamp * 1000  // 文章创建时间戳
})

// 验证编辑框是否为空
function validateEditPost() {
  if (updatePost.value.title === '') {
    editBtn.value = false  // 禁用编辑按钮
  } else {
    editBtn.value = true  // 启用编辑按钮
  }
}

// 修改文章
function editPost() {
  editBtn.value = false  // 禁用编辑按钮  
  
  // 将图片ID列表转换为字符串
  updatePost.value.image_ids = Object.values(uploadImageObj.value).join(',')
  
  const fetchConfig = {
    method: 'post',
    headers: { Authorization: 'Bearer ' + token },
    url: backedHost + '/post/update',
    data: updatePost.value
  }
  axios(fetchConfig)
    .then((response) => {
      if (response.data.code === 2000) {
        message.success('修改成功！')
        window.setTimeout(() => {
          showEditModal.value = false  // 关闭编辑弹窗
          toIndex()
        }, 1000)
      }
      editBtn.value = true  // 启用编辑按钮            
    })
    .catch((error) => {
      console.log(error)
      editBtn.value = true  // 启用编辑按钮
      message.error(error.response.data.message)
      // 将所有 ref 变量置空
    })
}
// 删除文章
function deletePost() {
  showDeleteModal.value = true  // 显示删除加载弹窗
  const fetchConfig = {
    method: 'post',
    headers: { Authorization: 'Bearer ' + token },
    url: backedHost + '/post/delete?id=' + postData.id,
    data: updatePost.value
  }
  axios(fetchConfig)
    .then((response) => {
      if (response.data.code === 2000) {
        message.success('删除成功！')
        window.setTimeout(() => {
          showDeleteModal.value = false  // 关闭删除加载弹窗
          toIndex()
        }, 1000)
      }
    })
    .catch((error) => {
      message.error(error.response.data.message)
      showDeleteModal.value = false  // 关闭删除加载弹窗
    })
}

// 返回首页
function toIndex() {
  if (window.location.pathname === '/index') {
    router.push('/')
  } else if (window.location.pathname === '/') {
    router.push('/index')
  }
  // 将修改过的图片数据置空
  uploadImageObj.value = {}
}

onBeforeUpdate(() => {
  // 验证编辑框是否为空
  validateEditPost();
  // 将图片对象列表赋值给上传图片对象
  for (const image of postData.image_list) {
    uploadImageObj.value[image.id] = image.id
  }
});
</script>

<template>
  <div class="post-action">
    <n-button type="info" :theme="darkTheme" style="margin-right: 10px;" @click="showEditModal = true">
      <n-icon class="icon-btn"><PostEditor /></n-icon>修改
    </n-button>
    <n-popconfirm :theme="darkTheme" negative-text="取消" positive-text="确定" :show-icon="false" @positive-click="deletePost()">
      <template #trigger>
        <n-button color="#d4237a" :theme="darkTheme">
          <n-icon class="icon-btn"><PostDelete /></n-icon>删除
        </n-button>
      </template>
      真的要删除吗？ 
    </n-popconfirm>
    <!-- 删除文章弹窗 -->
    <n-modal v-model:show="showDeleteModal" :mask-closable="false">
      <n-spin size="large" />
    </n-modal>

    <!-- 更新文章弹窗 -->
    <n-modal v-model:show="showEditModal" :mask-closable="false">
      <n-card style="width: 90%" :theme="darkTheme" title="修改文章" :bordered="false" size="huge" role="dialog" aria-modal="true">
        <!-- 文章标题 -->
        <n-input-group>
          <n-button color="#F6F5F5" ghost>标题</n-button>
          <n-input v-model:value="updatePost.title" type="text" placeholder="请输入标题（必填）" :theme="darkTheme" clearable/>
        </n-input-group>
        <!-- 日期选择 -->
        <div class="post-action-group">
          <n-input-group>
            <n-button color="#F6F5F5" ghost>日期</n-button>
            <n-date-picker input-readonly	v-model:value="updatePost.create_timestamp" type="datetime" clearable style="width: 100%;"/>
          </n-input-group>
        </div>
        <!-- 文章内容 -->
        <div class="post-action-group">
          内容：
          <n-input v-model:value="updatePost.content" type="textarea" placeholder="请输入内容" :theme="darkTheme" clearable/>
        </div>                
        <!-- 图片上传 -->
        <div class="post-action-group">
          <n-upload
            :default-file-list="postData.image_list"
            accept="image/*"
            :theme="darkTheme"
            :action="backedHost + '/image/upload_image'"
            list-type="image-card"
            name="image"
            :headers="{Authorization: 'Bearer ' + token}"
            @remove="deleteImage"
            @before-upload="(_) => {editBtn = false}"
            @error="(_) => {editBtn = true;message.error('上传失败，请重试！')}"
            @finish="(fileData) => {editBtn = true;uploadImageObj[fileData.file.id] = JSON.parse(fileData.event.currentTarget.response).data.id;message.success('上传成功！')}"
          >
            上传新图
          </n-upload>
        </div>
        <!-- 修改按钮 -->
        <template #footer>
          <n-button color="#52D3D8" :theme="darkTheme" style="width: 100%;" :disabled="!editBtn" @click="editPost()">修改</n-button>          
          <n-button color="#d4237a" :theme="darkTheme" style="width: 100%;margin-top: 10px;" :disabled="!editBtn" @click="showEditModal = false">取消</n-button>
        </template>
      </n-card>
    </n-modal>
  </div>
</template>

<style>
.post-action-group {
  margin-top: 10px;
}
</style>
